The Developer Fastlane

« 365 days to become a developer » challenge

SQL: Add & modify data

November 25, 2020

Easiest and commonly used method

Method to add or modify a table's data

In general, to insert SQL code into PHP (as part of a query to or from the database), one can use the generator built into phpMyAdmin:
  1. Select the database in the left menu, then select the table to be modified.
  2. Click on the "SQL" tab
  3. Click on the buttons below the textarea: SELECT *, SELECT, INSERT, UPDATE or DELETE depending on your needs.

Syntax rules:

  • Queries are separated by semicolons ";"
  • Values are separated by commas ","
    • Strings: always surround by double quotes OR simple quotes (both work fine)
    • Numbers: no need of simple nor double quotes
    • Floats: use a point before decimals (no comma, unlike we do in france)
    • DATE and DATETIME : are in US format Y/m/d h:i:s. You can either use "/" or "-" as separators for the date, MySQL will automatically understand that the values are separated.

Conditional operators / selectors

These are to use after the WHERE statement
  • OR, AND,...
    • We use brackets to prioritize conditions.
    • Example: SELECT * FROM users WHERE city = "Paris" AND (firstname = "john OR firstname = "marc");
  • IN (array): in case of complex conditions, instead of using series of OR, we can use this syntax: SELECT * FROM table_name WHERE column_name IN (value1, value2, value3);It works for both numbers and strings.
  • Equals to, Different from, ...
    • Equals to: with = sign
    • different from: with <!= (or <>) signs
    • Bigger than / Smaller than: >, >= / <, <=
  • LIMIT 2, 4 means "only 4 lines, starting on line 2". Be carefull: First line is ranked 0, so when we write 2 as a strating point, the query will return from the 3rd line of the table (line 2 = 3rd line).
  • When we need to select all fields for a query: instead of listing them all, the magic character * will allows to select all. Example: SELECT * FROM users will select all fields of the "users" table. Warning: This has a performance downturn. That's why it's recommanded to define each field one by one if possible.

If using Command lines

List of queries:
  1. INSERT TO : key points / video
  2. DELETE FROM : key points / video
  3. UPDATE : key points / video
  4. SELECT : key points / video

1. INSERT TO

Code
INSERT INTO table_name (field1, field2) VALUES   
    ("value1_line1", "value2_line1"),
    ("value1_line2", "value2_line2");
Exemple:
    INSERT INTO users (firstname, surname) VALUES   
        ('Dwayne', 'Johnson'),
        ('Will', 'Smith');

Key points

  • Columns that are not set with any default value will require one while doing a INSERT TO on them.

2. DELETE FROM

To delete lines:
Code
DELETE FROM table_name WHERE condition(s) [LIMIT number_of_lines];

Examples:
   
    DELETE FROM users WHERE id = "4";
        // Will delete the user whose id is 4.

    DELETE FROM users WHERE firstname = "Dayne" LIMIT 1;
        // Will delete only the first line in which firstname is set to "Dayne"
To empty a table:
Code
TRUNCATE TABLE table_name

Example:

    TRUNCATE TABLE users

Key points:

  • Deleted data can't be recovered, it's definite (no backup system): use LIMIT 1 by default at the end of the request (change 1 by the max number of lines to delete)
  • For the condition, in general, the id is used as a selection criterion: DELETE FROM users WHERE id="4" LIMIT 1; for example
  • A deleted id is NEVER reassigned (auto-increment continues as if no line has been deleted)
  • To delete an entire table AND its properties and reset auto-increment, use: TRUNCATE table_name;
  • Using: DELETE FROM table_name; without passing any WHERE parameter will empty the table, but the properties and auto-increment will not be reset. TRUNCATE allows you to reassign the ids to a new table.
  • It is possible to use OR and AND in the condition. examples:
Code
DELETE FROM users WHERE id = 1 OR id = 3;
    // Will remove users whose ids are equals to 1 or 3

DELETE FROM users WHERE town = "Paris" AND age < 18 ;
    // Will remove all users under 18 years old living in Paris

3. UPDATE

Code
UPDATE table_name SET field1=value1 [, field2=value2, ...] WHERE condition(s);

Examples:

    UPDATE table_name SET town="Paris", gender="h" WHERE id = 4 OR id = 6;
        // Will update "town" and "gender" values for users whose ids are either 4 and 6

Key points:

  • As for DELETE, UPDATE function will by default change all fields. Tha's why we set conditions using a WHERE statement.
  • You can also use LIMIT 1 for example to secure the command and be sure to change only one line.
  • You can use the arrhythmia functions (more about that later) after WHERE and SET statements. Example:
Code
UPDATE users SET surname = firstname ; 
ALTER TABLE users DROP firstname ;
    // Will change the last name to the first name value for all users (then delete the first name column)

4. SELECT

Select data: SELECT

Code
SELECT field1 [field2, ...] 
    FROM database_name WHERE condition(s) 
    LIMIT number_of_lines

Example:

    SELECT surname, firstname FROM users LIMIT 2, 5;
    
    // Will get values for "surname" and "firstname" fields for lines 2 to 5 in "users" table

Reorder data: GROUPE BY

Code
    SELECT column1 [, column2, ...] 
        FROM table_name 
        [ ORDER BY column1 [ASC/DESC] [, column2, ...] ]

Example:
    
    SELECT * 
        FROM users 
        ORDER BY surname DESC, id DESC

    // Will return all users, decreasingly sorted based on the "surname" column (so, form A to Z in this case as the column is set on VARCHAR)
    // And if several lines have the same value for "surname", then these will be decreasingly sorted base on their "id" (so from 0 to 65,536 as id is set to SMALLINT)

Count data: COUNT

Code
SELECT COUNT(target_column1 [, target_column2, ...]) AS choose_a_name 
    FROM table_name
    
Example:

    SELECT COUNT(id) AS population 
        FROM users
        
    // Will return an integers (example: 4) which corresponds to the total number of lines in the "users" table
    // Output : 'population' => 4
COUNT won't return NULL values contained in target_column. For example, if we choose to count "surname" column, and if a surname is missing for a line (empty field), then the count will be équal to: total_lines - 1.

Group returned data: GROUP BY

Code
Example:
SELECT COUNT(id) AS pouplation, gender
    FROM users
    GROUP BY gender;
    
// Output: 'female' => 1, 'male' => 3

Some more usefull function to make granular selections

  • SELECT MAX(column) : will return the highest value of the defined range of data
  • SELECT MIN(column) : will return the smallest value
  • SELECT AVG(column) : will return the average value for the range (only for numeric values)
  • LIKE function: allows to make partial research base on specifical string patterns. Very usefull! Example:
Code
SELECT * FROM users WHERE surname LIKE "J%";
    // Will return a list of users whose surname starts with "J"

SELECT * FROM users WHERE firstname LIKE "%h%"
    // Will return a list of users whose firstname contains the letter "h"
    
SELECT * FROM users WHERE email LIKE "%gmail.com"
    // Will return a list of users who are using Gmail as an email service provider
© 2020 - Edouard Proust | The Developer Fastlane